package cn.antblog.poi.ppt;

import org.apache.poi.sl.usermodel.TextShape;
import org.apache.poi.xslf.usermodel.*;

import java.io.*;
import java.util.List;

/**
 * @author YangJingyi
 * @date 2021-12-06 14:15
 */
public class GenerateTempPpt  {


    /**
     * 读取ppt文件流
     * @return
     * @throws Exception
     */
    public static InputStream readTemplateInput() throws Exception {
        FileInputStream fileInputStream=new FileInputStream(new File("C:\\Users\\YangJingyi\\Desktop\\kdmb.pptx"));
        return fileInputStream;
    }
    /**
     * 将文件流转pptx
     */
    public static XMLSlideShow convertPPtx(InputStream inputStream) throws IOException {
        XMLSlideShow xmlSlideShow=new XMLSlideShow(inputStream);
        return xmlSlideShow;
    }

    /**
     * 分析pptx
     */
    public XMLSlideShow analysePPTX(XMLSlideShow xmlSlideShow) throws Exception {
        //返回演示文稿中的所有幻灯片。
        List<XSLFSlide> slides = xmlSlideShow.getSlides();

        for (XSLFSlide slide : slides) {
            //获取ppt形状
            List<XSLFShape> shapes = slide.getShapes();
            for (XSLFShape shape : shapes) {
                //判断是否是 文本
                if(shape instanceof TextShape){
                    //获取所有文本的段落
                    List<XSLFTextParagraph> textParagraphs = ((TextShape) shape).getTextParagraphs();
                    //遍历文本内容
                    if(textParagraphs!=null && textParagraphs.size()>0){
                        for (XSLFTextParagraph textParagraph : textParagraphs) {
                            System.out.println("文本："+textParagraph.getText());
                        }
                    }else {
                        System.out.println("文本：XXXXXXXXXXXXXXXXXXX");
                    }
                    replaceTextShape(textParagraphs);
                }
            }
        }
        return xmlSlideShow;
    }

    private void replaceTextShape(List<XSLFTextParagraph> textParagraphs) {
        if(textParagraphs==null||textParagraphs.size()==0){
            return;
        }
        for (XSLFTextParagraph textParagraph : textParagraphs) {
            if(textParagraph==null){
                continue;
            }
            List<XSLFTextRun> textRuns = textParagraph.getTextRuns();
            if(textRuns==null){
                continue;
            }
            for (XSLFTextRun textRun : textRuns) {
                System.out.println("textRun:"+textRun.getRawText());
                textRun.setText(textRun.getRawText().replace("{customer}","中国移动"));
            }
        }
    }


    public static void main(String[] args) throws Exception{
        GenerateTempPpt g=new GenerateTempPpt();
        g.analysePPTX(g.convertPPtx(g.readTemplateInput())).write(new FileOutputStream("C:\\Users\\YangJingyi\\Desktop\\kd.pptx"));
    }

}
